<template>
  <div ref="chartRef" :style="`height:${height}`"/>
</template>

<script lang="ts">
import { defineComponent, getCurrentInstance, onMounted, onBeforeUnmount, ref, watch } from "vue";
import * as echarts from "echarts";

let chartsArr:any = [];
export default defineComponent({
  name: "BaseChart",
  props: {
    options: {
      type: Object,
      default: () => ({})
    },
    height:{
      type: String,
      default: '50vh'
    }
  },
  setup(props) {

    // @ts-ignore
    const { proxy } = getCurrentInstance();
    const instanceId = ref('')
    const initCharts = () => {
      const chart = echarts.init(proxy.$refs.chartRef);
      chart.setOption(props.options);
      chartsArr.push(chart);
      instanceId.value = chart.id
    };
    const updateChart = () => {
      // @ts-ignore
      const target = chartsArr.find((v) => v.id === instanceId.value)
      if (target) {
        // 清空画布
        target.clear()
        target.resize()
        // 重新设置配置项
        target.setOption(props.options)
      }
    }
    watch(
      () => props.options,
      () => {
        updateChart()
      },
      {
        deep: true,
      }
    )
    const resizeCharts = () => {
      for(var i = 0;i < chartsArr.length;i++) {
        chartsArr[i] && chartsArr[i].resize();
      }
    };
    onMounted(() => {
      initCharts();
      window.addEventListener("resize", resizeCharts);
    });
    onBeforeUnmount(() => {
      // 移除窗口resize事件
      window.removeEventListener('resize', resizeCharts);;
    });
    return {
    };
  }
});
</script>
